import array
import serial
import threading
import numpy as np
import time
import pyqtgraph as pg
import websocket
from threading import Thread
import sys
import struct

gKBs = 0
start_time = time.time()
historyLength = 20000
y_height = 255
data = np.array([], dtype="float32")

def on_error(ws, error):
  print(error)
 
def on_close(ws):
  print("### closed ###")
 
def on_open(ws):
  def run(*args):
    # send the message, then wait
    # so thread doesn't exit and socket
    # isn't closed
    print("send: setRepeatRequest")
    global start_time
    start_time = time.time()
    ws.send("setRepeatRequest")
  Thread(target=run).start()
 
proflie_ts =  time.time()
def on_data(ws, message, type, flag):
  # print("on_data rec: type:", (type))
  # print(message)
  global proflie_ts
  global gKBs
  global data
  gKBs = gKBs + 1
  speed = gKBs*10/(time.time() - start_time)
  # print(message)
  if (time.time() - proflie_ts > 2):
    print("rec ts_span:",'%.1f' % ((time.time() - proflie_ts)*1000), "speed",'%.3f' % speed, "KB/s")
  proflie_ts = time.time()
  msgarray = bytearray(message)
  # byte 2 float array
  msgfloat32_array = np.frombuffer(message, dtype=np.float32)
  #print(msgfloat32_array)
  
  #除3余1
  test1 = msgfloat32_array[::3] #电流
  #除3余2
  test2 = msgfloat32_array[1::3] #电压
  #整除3
  test3 = msgfloat32_array[2::3] #功率

  data = np.append(data, test3)
  if (time.time() - proflie_ts > 2):
        print("rec proc time:",'%.1f' % ((time.time() - proflie_ts)*1000),"ms")
  proflie_ts = time.time()


def webSocketStart():
  print("begin")
  websocket.enableTrace(True)
  host = "ws://192.168.0.103/"
  ws = websocket.WebSocketApp(host,
                #on_message=on_message,
                on_error=on_error,
                on_close=on_close,
                on_data = on_data)
  ws.on_open = on_open
  ws.run_forever()



def DataSrcSocket():
    webSocketStart()

def plotData():
    curve.setData(data)
    print("avg:", np.mean(data))
    global historyLength
    global y_height
    if (len(data) >= historyLength):
        historyLength = historyLength * 2
        y_height = y_height * 2
        p.setRange(xRange=[0, historyLength], yRange=[0, y_height], padding=0)


if __name__ == "__main__":
    app = pg.mkQApp()  # 建立app
    win = pg.GraphicsWindow()  # 建立窗口
    win.setWindowTitle(u'pyqtgraph逐点画波形图')
    win.resize(800, 300)  # 小窗口大小
    historyLength = 200000  # 横坐标长度
    a = 0

    p = win.addPlot()  # 把图p加入到窗口中
    p.showGrid(x=True, y=True)  # 把X和Y的表格打开
    p.setRange(xRange=[0, historyLength], yRange=[0, y_height], padding=0)
    p.setLabel(axis='left', text='y / V')  # 靠左
    p.setLabel(axis='bottom', text='x / point')
    p.setTitle('semg')  # 表格的名字
    curve = p.plot()  # 绘制一个图形
    curve.setData(data)

    # 获取数据
    th1 = threading.Thread(target=DataSrcSocket)
    th1.start()

    timer = pg.QtCore.QTimer()
    timer.timeout.connect(plotData)  # 定时刷新数据显示
    timer.start(100)  # 多少ms调用一次
    app.exec_()
